package com.msdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msdp.dto.Result;
import com.msdp.dto.UserDTO;
import com.msdp.entity.Follow;
import com.msdp.entity.User;
import com.msdp.mapper.FollowMapper;
import com.msdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msdp.service.IUserService;
import com.msdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.msdp.utils.MessageConstants.NOT_LOGIN;
import static com.msdp.utils.RedisConstants.FOLLOW_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;
    /**
     * 关注/取消关注
     * @param id
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long id, Boolean isFollow) {
        // 判断用户是否登录
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail(NOT_LOGIN);
        }
        // 判断是关注操作还是取关操作
        // 关注
        String key = FOLLOW_KEY + user.getId();
        if(BooleanUtil.isTrue(isFollow)){
            Follow follow = new Follow();
            follow.setUserId(user.getId());
            follow.setFollowUserId(id);
            boolean isSuccess = save(follow);
            if(isSuccess){
                // 把关注用户的id，放入redis的集合
                stringRedisTemplate.opsForSet().add(key, id.toString());
            }
        }else {
            //取消关注
            QueryWrapper<Follow> followQueryWrapper = new QueryWrapper<>();
            followQueryWrapper.eq("user_id", user.getId()).eq("follow_user_id", id);
            boolean isSuccess = remove(followQueryWrapper);
            if(isSuccess){
                // 把关注用户的id，从redis集合中删除
                stringRedisTemplate.opsForSet().remove(key, user.getId().toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询用户是否关注
     * @param id
     * @return
     */
    @Override
    public Result isFollow(Long id) {
        // 判断用户是否登录
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail(NOT_LOGIN);
        }
        Integer count = query().eq("user_id", user.getId()).eq("follow_user_id", id).count();
        return Result.ok(count > 0);
    }

    /**
     * 获取共同关注
     * @param followId
     * @return
     */
    @Override
    public Result getCommon(Long followId) {

        Long userId = UserHolder.getUser().getId();
        String userKey = FOLLOW_KEY + userId;

        String followKey = FOLLOW_KEY + followId;

        Set<String> set = stringRedisTemplate.opsForSet().intersect(userKey, followKey);

        if(set == null || set.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        // 查询用户信息
        List<User> users = userService.listByIds(ids);
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 返回
        return Result.ok(userDTOS);
    }
}
